CREATION, INDEXING, SLICING, AND OPERATIONS
Lists in Python are versatile data structures that can hold a collection of items. They are ordered, mutable, and can contain elements of different data types. Lists are created using square brackets [ ]
and can be indexed, sliced, and manipulated with various operations.
- Creation of Lists: To create a list, you enclose its elements in square brackets, separated by commas.
Example:
python
# Creating a list of integers
numbers = [1, 2, 3, 4, 5]
# Creating a list of strings
fruits = ["apple", "banana", "orange"]
# Creating a mixed-type list
mixed_list = [1, "hello", 3.14, True]
- Indexing: You can access individual elements of a list using their index. Indexing in Python starts from 0 for the first element, 1 for the second element, and so on. Negative indexing allows you to access elements from the end of the list, starting with -1 for the last element.
Example:
python
numbers = [1, 2, 3, 4, 5]
print(numbers[0]) # Output: 1
print(numbers[3]) # Output: 4
print(numbers[-1]) # Output: 5 (last element)
print(numbers[-3]) # Output: 3 (third element from the end)
- Slicing: Slicing allows you to extract a portion of a list by specifying a range of indices. It is done using the colon
:
. The slice notationlist[start:stop:step]
extracts elements from indexstart
up to (but not including) indexstop
, with an optionalstep
indicating the interval between elements.
Example:
python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[2:6]) # Output: [3, 4, 5, 6]
print(numbers[:5]) # Output: [1, 2, 3, 4, 5] (start is omitted, starts from the beginning)
print(numbers[5:]) # Output: [6, 7, 8, 9, 10] (stop is omitted, goes up to the end)
print(numbers[1:9:2]) # Output: [2, 4, 6, 8] (step of 2, every second element)
print(numbers[::-1]) # Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] (reverses the list)
- List Operations: You can perform various operations on lists, such as adding elements, concatenating lists, removing elements, and more.
Example:
python
fruits = ["apple", "banana", "orange"]
# Add an element to the end of the list
fruits.append("grape")
print(fruits) # Output: ['apple', 'banana', 'orange', 'grape']
# Concatenate two lists
more_fruits = ["pear", "kiwi"]
all_fruits = fruits + more_fruits
print(all_fruits) # Output: ['apple', 'banana', 'orange', 'grape', 'pear', 'kiwi']
# Remove an element by value
fruits.remove("banana")
print(fruits) # Output: ['apple', 'orange', 'grape']
# Get the length of the list
print(len(fruits)) # Output: 3
These are some of the fundamental concepts related to lists in Python. Lists are widely used due to their flexibility and ability to hold multiple elements of different types in an ordered sequence.